package com.example.qt.ptplatform.controller;

import com.example.qt.ptplatform.entity.Promotions;
import com.example.qt.ptplatform.service.PromotionsService;
import com.example.qt.ptplatform.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/promotions")
public class PromotionsController {

    @Autowired
    private PromotionsService promotionsService;

    // 创建促销活动
    @PostMapping("/add")
    public JsonResult createPromotion(@RequestBody Promotions promotions) {
        try {
            // 调用服务层方法创建促销活动
            long promoId = promotionsService.createPromotion(promotions);
            return JsonResult.success(String.valueOf(promoId)); // 返回活动ID
        } catch (IllegalArgumentException e) {
            return JsonResult.error("活动时间设置不正确，请重新设定。");
        } catch (Exception e) {
            return JsonResult.error("活动创建失败，请稍后重试。");
        }
    }

    //根据促销id获取促销详情
    @GetMapping("/{promo_id}")
    public JsonResult getPromotionDetails(@PathVariable long promo_id) {
        try {
            //调用服务层方法获取促销活动详情
            Promotions promotions = promotionsService.getPromotionDetails(promo_id);
            //判断是否获取达到有效的促销活动
            if(promotions != null) {
                return JsonResult.success(promotions);
            }else {
                return JsonResult.error("该促销活动不存在");
            }
        }catch (Exception e) {
            return JsonResult.error("获取促销活动详情失败");
        }
    }

    //获取促销活动列表，支持分页
    @GetMapping("/list")
    public JsonResult getPromotionList(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "per_page", defaultValue = "10") int per_page) {
        try {
            //调用服务层方法获取分页数据
            List<Promotions> promotionsList = promotionsService.getPromotionList(page, per_page);
            long total = promotionsService.getPromotionCount(); // 获取总条数

            // 返回响应数据
            return JsonResult.success(promotionsList, total);
        }catch (Exception e) {
            return JsonResult.error("获取促销活动列表失败");
        }
    }

    //删除指定促销id的促销活动
    @DeleteMapping("/delete/{promo_id}")
    public JsonResult deletePromotion(@PathVariable long promo_id) {
        try {
            boolean isDeleted = promotionsService.deletePromotion(promo_id);
            if (isDeleted) {
                return JsonResult.success("促销活动删除成功");
            } else {
                return JsonResult.error("促销活动不存在");
            }
        }catch (Exception e) {
            return JsonResult.error("Error occurred while deleting the promotion.");
        }
    }

    /**
     * 获取用户进入种子详情页面时，最优惠的促销活动（下载量系数最小）
     * @param userId 用户ID
     * @param torrentId 种子ID
     * @return 返回最优惠的促销活动
     */
    @GetMapping("/getBestDownloadPromo/{userId}/{torrentId}")
    public JsonResult getBestPromoForUser(@PathVariable("userId") Long userId, @PathVariable("torrentId") Long torrentId) {
        try {
            // 查询最优惠的促销活动（下载量系数最小）
            List<Promotions> bestPromo = promotionsService.getBestDownloadPromo(userId, torrentId);
            if (bestPromo.isEmpty()) {
                return JsonResult.error("没有符合条件的促销活动");
            }
            return JsonResult.success("查询成功", bestPromo);
        } catch (Exception e) {
            return JsonResult.error("发生错误，查询促销活动失败", e.getMessage());
        }
    }

    /**
     * 用户上传种子时，查询最优惠的促销活动（上传量系数最大）
     * @param userId 用户ID
     * @return 返回最优惠的促销活动
     */
    @GetMapping("/getBestUploadPromo/{userId}")
    public JsonResult getBestUploadPromoForUser(@PathVariable("userId") Long userId) {
        try {
            // 查询最优惠的促销活动（上传量系数最大）
            Promotions bestPromo = promotionsService.getBestUploadPromo(userId);
            if (bestPromo == null) {
                return JsonResult.error("没有符合条件的促销活动");
            }
            return JsonResult.success("查询成功", bestPromo);
        } catch (Exception e) {
            return JsonResult.error("发生错误，查询促销活动失败", e.getMessage());
        }
    }
}
